跳到主要内容

2 两数相加

https://leetcode.cn/leetbook/read/top-interview-questions-medium/xvw73v/

cost: 27m58s

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
auto head = l1;
int carry = 0;
while (l1 != nullptr && l2 != nullptr) {
int val = l1->val + l2->val + carry;
carry = val / 10;
l1->val = val % 10;
if (l1->next == nullptr || l2->next == nullptr) {
break;
}
l1 = l1->next;
l2 = l2->next;
}
if (l1->next == nullptr) {
l1->next = l2->next;
}
if (l1->next == nullptr) {
if (carry != 0) {
l1->next = new ListNode(carry);
return head;
}
}
l1 = l1->next;
while (l1 != nullptr) {
int val = l1->val + carry;
carry = val / 10;
l1->val = val % 10;
if (l1->next == nullptr) {
break;
}
l1 = l1->next;
}
if (carry != 0) {
l1->next = new ListNode(carry);
}
return head;
}
};